package com.jp.knowledge.activity;

import android.content.BroadcastReceiver;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Messenger;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dmcc.image_preview.ImagePreviewActivity;
import com.github.anzewei.parallaxbacklayout.ParallaxHelper;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.adapter.InfoDataDetailImgAdapter;
import com.jp.knowledge.animation.JingIconAnimation;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.comm.JpApplication;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.dialog.CommDialog;
import com.jp.knowledge.dialog.CopyrightDialog;
import com.jp.knowledge.dialog.InfoDetailCommentDialog;
import com.jp.knowledge.dialog.InfoDetailSharePopupWindow;
import com.jp.knowledge.dialog.InfoDetailToolsPopupWindow;
import com.jp.knowledge.dialog.SelectDialog;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.http.ToutiaoGetDataUtil;
import com.jp.knowledge.model.BigDataModel;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.InfoData;
import com.jp.knowledge.model.InfoDetailStateModel;
import com.jp.knowledge.model.TopicListInfo;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.my.activity.FeedbackCreateActivity;
import com.jp.knowledge.my.activity.IntegralBuyActivity;
import com.jp.knowledge.my.activity.ToBeVipOrganize;
import com.jp.knowledge.my.activity.VipActivity;
import com.jp.knowledge.my.base.RecycleVAdapter;
import com.jp.knowledge.my.model.OrganizaModel;
import com.jp.knowledge.util.JsonUtil;
import com.jp.knowledge.util.L;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.util.ShareBuilder;
import com.jp.knowledge.view.BigDataView;
import com.jp.knowledge.view.JpDiver;
import com.jp.knowledge.view.JpNewsDetailWebView;
import com.jp.knowledge.view.JpWebView;
import com.jp.knowledge.view.TalkBottomBarView;
import com.jp.knowledge.comm.InfoDetailData;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.WebSettings.TextSize;
import com.tencent.smtt.sdk.WebView;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.media.UMImage;

import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import static com.jp.knowledge.broad.LocalBroadCast.GET_LOGIN_INFO;
import static com.jp.knowledge.util.UrlManager.SHARE_BASE_URL;


/**
 * Created by 528787067@qq.com on 2017/1/9.
 */
public class InfoDataDetailActivity extends SlidingActivity implements View.OnClickListener, TalkBottomBarView.TalkBottomBarCallback, ToutiaoGetDataUtil.GetDataCallback, ResultSubscriber.OnResultListener {

    private static final int COMMETN_CODE = 0x01;
    private static final int PAY_CODE = 0x02;
    private static final String HOST_URL = SHARE_BASE_URL + "/headlines#/headlines/content?";

    @ViewInject(R.id.permissionRemindView)
    private FrameLayout permissionRemindView;
    @ViewInject(R.id.permissionView)
    private LinearLayout permissionView;
    @ViewInject(R.id.loading_view)
    private RelativeLayout loadingView;
    @ViewInject(R.id.reload_view)
    private TextView reloadView;
    @ViewInject(R.id.remind_img)
    private ImageView remindImg;
    @ViewInject(R.id.remind_text)
    private TextView remindText;
    @ViewInject(R.id.remind_btn)
    private TextView remindBtn;
    @ViewInject(R.id.top_return)
    private ImageView returnView;
    @ViewInject(R.id.shade_view)
    private View shadeView;
    @ViewInject(R.id.j_right_icon)
    private RelativeLayout rightIcon;
    @ViewInject(R.id.detial_search_icon)
    private ImageView deatilSearchIcon;
    @ViewInject(R.id.detial_search_text)
    private TextView deatilSearchText;
    @ViewInject(R.id.talk_bottom)
    private TalkBottomBarView talkBottomView;
    @ViewInject(R.id.copyright_btn)
    private TextView copyrightBtn;

//    @ViewInject(R.id.verticalViewPager)
//    private VerticalViewPager verticalViewPager;
//    private List<View> contentViews;
    private FrameLayout mainWebContent;
    @ViewInject(R.id.reload_detail)
    private TextView reloadDetail;
    @ViewInject(R.id.main_web_view)
    private JpNewsDetailWebView jpWebView;
    private BigDataView bigDataView;

    @ViewInject(R.id.mainRvFrame)
    private FrameLayout mainRvFrame;
    @ViewInject(R.id.mainRv)
    private RecyclerView mainRv;
    @ViewInject(R.id.mainRvText)
    private TextView mainRvText;

    private View showMoreView;
    private TextView setTextSizeBtn;
    private TextView adjustSortBtn;
    private TextView feedbackBtn;

    private String webParam;        // 用于判断是否是从 HTML 跳过来的
    private InfoDetailData infoDetailData;
    private ToutiaoGetDataUtil getDataUtil;
    private List<String> imgPaths;
    private BroadcastReceiver broadcastReceiver;
    private LocalBroadcastManager localBroadcastManager;
    private ShareAction shareAction;

    private PopupWindow moreBtnPopupWindow;
    private SelectDialog fontSelectDialog;
    private InfoDetailSharePopupWindow sharePopupWindow;
    private InfoDetailToolsPopupWindow toolsPopupWindow;
    private CommDialog payDialog;
    private InfoDetailCommentDialog commentDialog;
    private CopyrightDialog copyrightDialog;

    private SharedPreferences sharedPreferences;

    @Override
    protected int getResourceId() {
        return R.layout.activity_info_data_detail_new;
    }

    @Override
    protected void init() {
        initDialog();
        sharedPreferences = getSharedPreferences("NewsDetail", MODE_PRIVATE);

        Intent intent = getIntent();
        infoDetailData = InfoDetailData.getInfoDetail();

        webParam = intent.getStringExtra("webParam");  // 如果是 H5 跳过来则带有此参数
        if(webParam != null){
            JsonObject json =  JsonUtil.getInstance().strToJson(webParam);
            infoDetailData.setLinkId(json.get("id").getAsString());
            infoDetailData.setlinkType(json.get("type").getAsInt());
//            talkBottomView.setContentViewStyle(3);
        } else {
            infoDetailData.setLinkId(intent.getStringExtra("id"));
            infoDetailData.setlinkType(intent.getIntExtra("type", 1));
            infoDetailData.setLinkIcon(intent.getStringExtra("linkIcon"));
            infoDetailData.setLinkTitle(intent.getStringExtra("linkTitle"));
            if(infoDetailData.getLinkType() == 6)
                talkBottomView.setContentViewStyle(3);
            else
                talkBottomView.setContentViewStyle(0);
        }
        talkBottomView.setShadeView(shadeView);
        talkBottomView.setTalkBottomBarCallback(this);

//        contentViews = new ArrayList<>();

//        mainWebContent = (FrameLayout) View.inflate(this, R.layout.activity_info_data_detail_webcontent, null);
//        jpWebView = (JpNewsDetailWebView) mainWebContent.findViewById(R.id.main_web_view);
//        reloadDetail = (TextView) mainWebContent.findViewById(R.id.reload_detail);
//        bigDataView = new BigDataView(this);
//        contentViews.add(mainWebContent);
//        contentViews.add(bigDataView);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(0x00000000);
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
            int statusBarHeight = 0;
            int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0)
                statusBarHeight = getResources().getDimensionPixelSize(resourceId);
            ((RelativeLayout.LayoutParams)returnView.getLayoutParams()).topMargin += statusBarHeight;
            ((RelativeLayout.LayoutParams)rightIcon.getLayoutParams()).topMargin += statusBarHeight;
        }

        initBroadcast();
        initViewPager();
        initWebView();
//        initBigDataView();
        showDataLoading();

        returnView.setOnClickListener(this);
        rightIcon.setOnClickListener(this);
        reloadDetail.setOnClickListener(this);
        remindBtn.setOnClickListener(this);
        reloadView.setOnClickListener(this);
        copyrightBtn.setOnClickListener(this);

        getDataUtil = new ToutiaoGetDataUtil(this);
        getDataUtil.setGetDataCallback(this);
        getDataUtil.getDetailData();        // 获取详情数据
        getDataUtil.getTopicData();         // 获取话题数据
        getDataUtil.getInfoDetailState();   // 获取资讯详情状态
    }

    private void initBroadcast(){
        // 登陆成功刷新界面
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                InfoData infoData = infoDetailData.getInfoData();
                if(infoData == null)
                    return;
                switch (infoData.getViewPermit()) {
                    case -1:    // -1 需先登录
                    case 1:     // 1 用户VIP可见
                    case 5:     // 5 企业VIP可见
                    case 6:     // 6 次数超过100
                    case 7:     // 7 次数超过1000
                        permissionView.setVisibility(View.GONE);
                        permissionRemindView.setVisibility(View.VISIBLE);
                        showDataLoading();
                        getDataUtil.getDetailData();
                        break;
                    case 0:     // 0 允许查看
                    case 2:     // 2 用户可见
                    case 3:     // 3 企业可见
                    case 4:     // 4 付费
                    default:
                        break;
                }
            }
        };
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        localBroadcastManager.registerReceiver(broadcastReceiver, new IntentFilter(GET_LOGIN_INFO));
    }

    private void initDialog() {
        showMoreView = View.inflate(mContext, R.layout.info_detail_select_dialog, null);
        setTextSizeBtn = (TextView) showMoreView.findViewById(R.id.set_font);
        setTextSizeBtn.setOnClickListener(this);
        adjustSortBtn = (TextView) showMoreView.findViewById(R.id.adjust_sort);
        adjustSortBtn.setOnClickListener(this);
        feedbackBtn = (TextView) showMoreView.findViewById(R.id.to_feekback);
        feedbackBtn.setOnClickListener(this);
        showMoreView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        moreBtnPopupWindow = new PopupWindow(showMoreView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        moreBtnPopupWindow.setOutsideTouchable(true);
        moreBtnPopupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));

        fontSelectDialog = new SelectDialog(mContext);
        fontSelectDialog.setTitle("字体大小");
        fontSelectDialog.addItem("小");
        fontSelectDialog.addItem("中");
        fontSelectDialog.addItem("大");
        fontSelectDialog.addItem("特大");
        fontSelectDialog.setCancelBtn("取消");
        fontSelectDialog.setOnDialogItemClickListener(new SelectDialog.OnSelectDialogItemClickListener() {
            @Override
            public void onSelectItemClick(int position) {
                setTextSizeLevel(position);
            }
        });

        payDialog = new CommDialog(mContext);
        payDialog.setTag(false);
        payDialog.setRightListener(this);

        commentDialog = new InfoDetailCommentDialog(mContext);
        commentDialog.setOnSendBtnClickListener(new InfoDetailCommentDialog.OnSendBtnClickListener() {
            @Override
            public void onSendClick() {
                String commentContent = commentDialog.getEditContent();
                if(commentContent.trim().length() == 0) {
                    ToasUtil.toast(mContext, "请输入有效内容后再提交");
                    return;
                }
                JsonObject param = new JsonObject();
                param.addProperty("content", commentContent);
                param.addProperty("type", infoDetailData.getLinkType());
                param.addProperty("infoId", infoDetailData.getLinkId());
                HttpHelper.getInstance(mContext).addComment(param, COMMETN_CODE, InfoDataDetailActivity.this);
                commentDialog.dismiss();
            }
        });
        talkBottomView.setOnCommentBtnClickListener(new TalkBottomBarView.OnCommentBtnClickListener() {
            @Override
            public void onCommentBtnClick(View v) {
                InfoData infoData = infoDetailData.getInfoData();
                if(infoData.getType() == 25){
                    if(infoData.getAppList() != null && infoData.getAppList().size() > 0)
                        toolsPopupWindow.show(v);
                } else {
                    commentDialog.show();
                }
            }
        });
        talkBottomView.setOnShareBtnClickListener(new TalkBottomBarView.OnShareBtnClickListener() {
            @Override
            public void onShareBtnClick(View shareBtn) {
                UserData userData = application.getUserData();
                if(userData != null && userData.getCompanyList() != null && userData.getCompanyList().size() > 0) {
                    List<OrganizaModel> companyList = userData.getCompanyList();
                    for(OrganizaModel organizaModel : companyList){
                        if(organizaModel.getCompanyState() != 1
                                || (organizaModel.getAuditStete() != 0 && organizaModel.getAuditStete() != 2)){
                            sharePopupWindow.visibilityTeamCircle(true);
                            sharePopupWindow.show(shareBtn);
                            return;
                        }
                    }
                }
                sharePopupWindow.visibilityTeamCircle(false);
                sharePopupWindow.show(shareBtn);
            }
        });
        toolsPopupWindow = new InfoDetailToolsPopupWindow(mContext);
        toolsPopupWindow.setToolsItemClickListener(new InfoDetailToolsPopupWindow.ToolsItemClickListener() {
            @Override
            public void onToolsItemClick(int position) {
                InfoData infoData = infoDetailData.getInfoData();
                InfoData.AppListBean data = infoData.getAppList().get(position);
                if(data.getAppName().contains("微信")){
                    String url = data.getAppUrl();
                    String title = infoData.getTitle();
                    String img = data.getAppIcon();
                    String remind = "扫码关注微信公众号";
                    QrCodeShowActivity.openQRCode(mContext, url, title, url, img, remind);
                } else{
                    WebBrowserActivity.openWebActivity(mContext, data.getAppUrl());
                }
            }
        });
        sharePopupWindow = new InfoDetailSharePopupWindow(mContext);
        sharePopupWindow.setOnShareItemClickListener(new InfoDetailSharePopupWindow.OnShareItemClickListener() {
            @Override
            public void onShareEmailClick() {
                if(!application.isLogin()){
                    startActivity(new Intent(mContext, LoginActivity.class));
                    return;
                }
                InfoData infoData = infoDetailData.getInfoData();
                if(infoData.getViewPermit() == 8){
                    UserData userData = application.getUserData();
                    if(userData != null) {
                        if (userData.getIntegralNum() >= infoData.getIntegral()) {
                            payDialog.setTag(true);
                            payDialog.setContent("是否确定支付" + infoData.getIntegral() + "知识币下载内容？");
                        } else {
                            payDialog.setTag(false);
                            payDialog.setContent("你当前知识币不足，是否充值知识币？");
                        }
                        isToDownload = true;
                        payDialog.show();
                    }
                    return;
                }
                toDownload();
            }
            @Override
            public void onShareTeamCircleClick() {
                Intent intent = new Intent(mContext, TeamCircleCreateActivity.class);
                intent.putExtra(TeamCircleCreateActivity.INTENT_TYPE, 3);
                intent.putExtra(TeamCircleCreateActivity.INTENT_LEVEL, 1);
                intent.putExtra(TeamCircleCreateActivity.INTENT_LINK_ICON, infoDetailData.getLinkIcon());
                intent.putExtra(TeamCircleCreateActivity.INTENT_LINK_ID, infoDetailData.getLinkId());
                intent.putExtra(TeamCircleCreateActivity.INTENT_LINK_TITLE, infoDetailData.getLinkTitle());
                intent.putExtra(TeamCircleCreateActivity.INTENT_LINKK_TYPE, infoDetailData.getLinkType());
                try {
                    OrganizaModel organizaModel = application.getUserData().getCompanyList().get(0);
                    intent.putExtra(TeamCircleCreateActivity.COMPANY_ID, organizaModel.getCompanyId());
                    intent.putExtra(TeamCircleCreateActivity.COMPANY_TYPE, organizaModel.getCompanyType());
                    intent.putExtra(TeamCircleCreateActivity.COMPANY_NAME, organizaModel.getCompanyName());
                } catch (Exception e){} finally {
                    mContext.startActivity(intent);
                }
            }
            @Override
            public void onShareOtherClick() {
                final InfoData infoData = infoDetailData.getInfoData();
                if(infoData == null) {
                    ToasUtil.toast(mContext, "内容为空!");
                    return;
                }
                if(shareAction == null) {
                    String url = HOST_URL + "id=" + infoData.getId() + "&type=" + infoData.getType();
                    ShareBuilder shareBuilder = new ShareBuilder(InfoDataDetailActivity.this)
                            .withTitle(mContext.getResources().getString(R.string.app_name))
                            .withText(infoData.getTitle())
                            .withCopyContent("【" + infoData.getTitle() + "】" + url)
                            .withTargetUrl(url)
                            .withQRCodeUrl(url);
                    try{
                        shareBuilder.withMedia(new UMImage(mContext, infoData.getInfoPic()));
                    } catch (Exception e){
                        shareBuilder.withMedia(new UMImage(mContext, R.mipmap.icon_launcher));
                    } finally {
                        shareAction = shareBuilder.build();
                    }
                }
                shareAction.open();
            }
        });
        copyrightDialog = new CopyrightDialog(mContext);

        talkBottomView.setCollectionListener(new TalkBottomBarView.CollectionListener() {
            @Override
            public void onCollection(boolean isCollection) {
                localBroadcastManager.sendBroadcast(new Intent(LocalBroadCast.DETAIL_SC_BROAD)
                        .putExtra("id", infoDetailData.getLinkId())
                        .putExtra("isCollection", infoDetailData.getInfoDetailStateModel().getIsFollow()));
            }
        });
    }

    private boolean isToDownload;
    private void toDownload(){
        InfoData infoData = infoDetailData.getInfoData();
        String url = infoData.getDownloadUrl();
        String title = infoData.getTitle();
        if(infoData.getFormat() != null)
            title += ("." + infoData.getFormat());
        String img = infoData.getInfoPic();
        String remind;
        double fileSize = infoData.getFileSize();
        if(fileSize < 1024)
            remind = String.format(Locale.getDefault(), "扫码即可下载(%.2fB)", fileSize);
        else if(fileSize < 1024 * 1024)
            remind = String.format(Locale.getDefault(), "扫码即可下载(%.2fk)", fileSize / 1024);
        else if(fileSize < 1024 * 1024 * 1024)
            remind = String.format(Locale.getDefault(), "扫码即可下载(%.2fM)", fileSize / 1024 / 1024);
        else
            remind = String.format(Locale.getDefault(), "扫码即可下载(%.2fG)", fileSize / 1024 / 1024 / 1024);
        QrCodeShowActivity.openQRCode(mContext, url, title, url, img, remind);
    }

    @Override
    protected void onResume() {
        super.onResume();
        talkBottomView.updateView();
    }

    @Override
    public void finish() {
        if(talkBottomView.activityFinish()) {
            if (webParam != null)
                application.getApplicationWebView().loadJavaScript("windowNativeBridge.backToHtml()");
            super.finish();
        }
    }

    /* 显示加载状态 */
    private void showDataLoading(){
        reloadDetail.setVisibility(View.GONE);
        jpWebView.getLoadingAnimationView().setVisibility(View.VISIBLE);
        reloadView.setVisibility(View.GONE);
        loadingView.setVisibility(View.VISIBLE);
    }

    /* 隐藏加载状态 */
    private void hideDataLoading(boolean showReload){
        jpWebView.getLoadingAnimationView().setVisibility(View.GONE);
        loadingView.setVisibility(View.GONE);
        if(showReload) {
            reloadDetail.setVisibility(View.VISIBLE);
            reloadView.setVisibility(View.VISIBLE);
        } else {
            reloadDetail.setVisibility(View.GONE);
            reloadView.setVisibility(View.GONE);
        }
    }

    /* 初始化垂直 ViewPager */
    private void initViewPager(){
//        verticalViewPager.setAdapter(new VerticalViewPager.PagerAdapter() {
//            @Override
//            public int getCount() {
//                return contentViews.size();
//            }
//            @Override
//            public boolean isViewFromObject(View view, Object object) {
//                return (view==object);
//            }
//            @Override
//            public void destroyItem(ViewGroup container, int position, Object object) {
//                super.destroyItem(container, position, object);
//                container.removeView(contentViews.get(position));
//            }
//            @Override
//            public Object instantiateItem(ViewGroup container, int position) {
//                container.addView(contentViews.get(position));
//                return contentViews.get(position);
//            }
//        });
//        verticalViewPager.setCurrentItem(0);
    }

    /* 初始化 webView */
    private void initWebView() {
        setTextSizeLevel(getTextSizeLevel());
        jpWebView.setShowReloadViewOnFail(false);
        jpWebView.setWebViewCallback(new JpWebView.WebViewCallback() {
            @Override
            public void onPageStarted(WebView webView, String s, Bitmap bitmap) {}
            @Override
            public void onPageFinished(WebView webView, String s) {
                hideDataLoading(false);
            }
            @Override
            public void onReceivedError(WebView webView, int i, String s, String s1) {
                hideDataLoading(false);
            }
            @Override
            public void onReceivedHttpError(WebView webView, WebResourceRequest webResourceRequest, WebResourceResponse webResourceResponse) {
                hideDataLoading(false);
            }
            @Override
            public void onReceivedTitle(WebView view, String title) {}
            @Override
            public void onProgressChanged(WebView view, int newProgress) {}
        });
        jpWebView.setJsCallbackListener(new JpWebView.JsCallbackListener() {
            @Override
            public void onJsCallback(JsonObject data) {
                try {
                    String key = data.get("key").getAsString();
                    if (key != null && key.equals("data")) {
                        imgPaths = new Gson().fromJson(data.get("param").getAsJsonArray(),
                                new TypeToken<List<String>>() {}.getType());
                    } else if (key != null && key.equals("click")) {
                        showImags(data.get("param").getAsInt());
                    } else if (key != null && key.equals("url")) {
                        String officialWebsite = data.get("param").getAsString();
                        if(officialWebsite != null && officialWebsite.trim().length() > 0)
                            WebBrowserActivity.openWebActivity(mContext, officialWebsite);
                    }
                } catch (Exception e){
                    L.e(e.toString());
                }
            }
        });
    }

    /* 初始化智能分析视图 */
    private void initBigDataView(){
        bigDataView.setBigDataLoadListener(new BigDataView.BigDataLoadListener() {
            @Override
            public void loadStart() {
                deatilSearchText.setVisibility(View.GONE);
                deatilSearchIcon.setVisibility(View.VISIBLE);
                deatilSearchIcon.startAnimation(new JingIconAnimation(1000, 10));
            }
            @Override
            public void loadFinish(BigDataModel bigDataModel) {
                deatilSearchIcon.clearAnimation();
                deatilSearchIcon.setVisibility(View.GONE);
                deatilSearchText.setVisibility(View.VISIBLE);
                deatilSearchText.setText(bigDataModel.getCount() + "");
            }
            @Override
            public void loadError() {
                deatilSearchText.setVisibility(View.GONE);
                deatilSearchIcon.clearAnimation();
                deatilSearchIcon.setVisibility(View.VISIBLE);
            }
        });
        InfoDetailData infoDetailData = InfoDetailData.getInfoDetail();
        bigDataView.setData(infoDetailData.getLinkId(), infoDetailData.getLinkType());
    }

    /* 点击查看大图 */
    private void showImags(int index) {
        ImagePreviewActivity.startActivity(this, index, (ArrayList<String>) imgPaths);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if((keyCode == KeyEvent.KEYCODE_BACK)
        && (shadeView.getVisibility() == View.VISIBLE/* || jpWebView.goBack()*/))
            return true;
        return super.onKeyDown(keyCode,event);
    }

    @Override
    protected void onDestroy() {
        jpWebView.destory();
        localBroadcastManager.unregisterReceiver(broadcastReceiver);
        infoDetailData.release();
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.top_return:
                onBackPressed();
                break;
            case R.id.j_right_icon:
//                verticalViewPager.setCurrentItem(contentViews.indexOf(bigDataView));
                if(permissionRemindView.getVisibility() != View.VISIBLE)
                    showSelectPop();
                break;
            case R.id.reload_view:
            case R.id.reload_detail:
                showDataLoading();
                getDataUtil.getDetailData();
                break;
            case R.id.set_font:
                moreBtnPopupWindow.dismiss();
                fontSelectDialog.show();
                break;
            case R.id.to_feekback:
                moreBtnPopupWindow.dismiss();
                Intent intent = new Intent(this, FeedbackCreateActivity.class);
                intent.putExtra(TeamCircleCreateActivity.INTENT_TYPE, 3);
                intent.putExtra(TeamCircleCreateActivity.INTENT_LEVEL, 1);
                intent.putExtra(TeamCircleCreateActivity.INTENT_LINK_ICON, infoDetailData.getLinkIcon());
                intent.putExtra(TeamCircleCreateActivity.INTENT_LINK_ID, infoDetailData.getLinkId());
                intent.putExtra(TeamCircleCreateActivity.INTENT_LINK_TITLE, infoDetailData.getLinkTitle());
                intent.putExtra(TeamCircleCreateActivity.INTENT_LINKK_TYPE, infoDetailData.getLinkType());
                try {
                    OrganizaModel organizaModel = application.getUserData().getCompanyList().get(0);
                    intent.putExtra(TeamCircleCreateActivity.COMPANY_ID, organizaModel.getCompanyId());
                    intent.putExtra(TeamCircleCreateActivity.COMPANY_TYPE, organizaModel.getCompanyType());
                    intent.putExtra(TeamCircleCreateActivity.COMPANY_NAME, organizaModel.getCompanyName());
                } catch (Exception e){} finally {
                    this.startActivity(intent);
                }
                break;
            case R.id.remind_btn:
                InfoData infoData = infoDetailData.getInfoData();
                int viewPermit = infoData.getViewPermit();
                if(viewPermit == -1 || viewPermit == 6){           // 登陆
                    startActivity(new Intent(mContext, LoginActivity.class));
                } else if(viewPermit == 1){   // 升级 VIP
                    startActivity(new Intent(mContext, VipActivity.class));
                } else if(viewPermit == 5 || viewPermit == 7){    // 成为 VIP 企业
                    startActivity(new Intent(mContext, ToBeVipOrganize.class));
                } else if(infoData.getViewPermit() == 4){    // 付费
                    try {
                        if (application.getUserData().getIntegralNum() >= infoData.getIntegral()) {
                            payDialog.setTag(true);
                            payDialog.setContent("是否确定支付" + infoData.getIntegral() + "知识币查看内容？");
                        } else {
                            payDialog.setTag(false);
                            payDialog.setContent("你当前知识币不足，是否充值知识币？");
                        }
                        payDialog.show();
                    } catch (Exception e){}
//                    startActivity(new Intent(mContext, PayPermissionActivity.class)
//                            .putExtra("title", "支付费用")
//                            .putExtra("payMoney", infoData.getIntegral())
//                            .putExtra("linkId", infoDetailData.getLinkId())
//                            .putExtra("linkIcon", infoDetailData.getLinkIcon())
//                            .putExtra("linkTitle", infoDetailData.getLinkTitle()));
                }
                break;
            case R.id.right_btn:
                if((boolean) payDialog.getTag()){
                    InfoData data = infoDetailData.getInfoData();
                    JsonObject param = new JsonObject();
                    param.addProperty("type", data.getType());
                    param.addProperty("id", data.getId());
                    param.addProperty("integral", data.getIntegral());
                    HttpHelper.getInstance(mContext).integralPurchase(param, PAY_CODE, this);
                } else{
                    startActivity(new Intent(mContext, IntegralBuyActivity.class));
                }
                break;
            case R.id.copyright_btn:        // 版权
                copyrightDialog.show();
                break;
            case R.id.adjust_sort:          // 校正管理
                moreBtnPopupWindow.dismiss();
                InfoData data = infoDetailData.getInfoData();
                startActivity(new Intent(mContext, AdjustSortActivity.class)
                        .putExtra("id", data.getId())
                        .putExtra("showCollection", data.getQiniuUrl() == null || data.getQiniuUrl().trim().length() == 0));
                break;
        }
    }

    /***
     * 显示一个 选择的Popuwindow
     */
    private void showSelectPop() {
        UserData userData = application.getUserData();
        if(userData == null || userData.getPlatformAdmin() != 1)
            adjustSortBtn.setVisibility(View.GONE);
        else
            adjustSortBtn.setVisibility(View.VISIBLE);
        showMoreView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        moreBtnPopupWindow.showAsDropDown(rightIcon,
                -showMoreView.getMeasuredWidth()+rightIcon.getWidth(), 0);
    }

    /* 设置权限显示 */
    private void setPermissionView(){
        reloadView.setVisibility(View.GONE);
        loadingView.setVisibility(View.GONE);
        InfoData infoData = null;
        if(infoDetailData != null)
            infoData = infoDetailData.getInfoData();
        permissionView.setVisibility(View.VISIBLE);
        remindImg.setImageResource(R.mipmap.no_data_hint);
        remindBtn.setVisibility(View.GONE);
        if(infoData == null){
            remindText.setText("暂时没有数据~");
        } else if(infoData.getState() == 0){
            remindText.setText("内容因版权问题已被删除");
        } else if(infoData.getState() == 2){
            remindImg.setImageResource(R.mipmap.message_prompt);
            remindText.setText("内容即将开放，敬请等候~");
        } else {
            remindText.setText(infoData.getViewPrompt());
            remindBtn.setVisibility(View.VISIBLE);
            remindBtn.setTag(infoData.getViewPermit());
            switch (infoData.getViewPermit()) {
                case -1:    // -1 需先登录
                case 6:     // 6 次数超过100
                    remindBtn.setText("登陆");
                    break;
                case 2:     // 2 用户可见
                case 3:     // 3 企业可见
                case 9:
                    remindBtn.setVisibility(View.GONE);
                    break;
                case 1:     // 1 用户VIP可见
                    remindBtn.setText("我要升级");
                    break;
                case 7:     // 7 次数超过1000
                    remindBtn.setText("我要成为VIP企业");
                    break;
                case 5:     // 5 企业VIP可见
                    UserData userData = application.getUserData();
                    if (userData == null || userData.getCompanyList() == null || userData.getCompanyList().size() == 0) {
                        remindBtn.setVisibility(View.GONE);
                        remindText.setText("你无权限阅读");
                    } else{
                        remindBtn.setText("我要成为VIP企业");
                    }
                    break;
                case 4:     // 4 付费（有两种付费方式）
//                    if(!TextUtils.isEmpty(infoData.getHtml())) {
//                        permissionRemindView.setVisibility(View.GONE);
//                    } else {
                        remindText.setText(String.format("需支付%d知识币才能查看", infoData.getIntegral()));
                        remindBtn.setText("付费");
//                    }
                    break;
                case 0:     // 0 允许查看
                default:
                    permissionRemindView.setVisibility(View.GONE);
            }
        }
    }

    /* 加载详情数据 */
    private void setDetailData() {
        InfoData infoData = infoDetailData.getInfoData();

        if(infoData.getId() == null) {
//            ToasUtil.toast(this, "抱歉，详情数据为空");
            hideDataLoading(false);
            return;
        }

//        if (infoData.getQiniuUrl() == null || infoData.getQiniuUrl().trim().length() == 0) {
//            talkBottomView.setContentViewStyle(0);
//        } else if(infoData.getQiniuUrl() != null && infoData.getQiniuUrl().trim().length() > 0) {
//            talkBottomView.setContentViewStyle(3);
//            if ((infoData.getUrl() == null || infoData.getUrl().trim().length() == 0)
//                    && (infoData.getHtml() == null || infoData.getHtml().trim().length() == 0)) {
//                talkBottomView.readDoc();
//                finish();
//            }
//        }

        if(infoData.getInfoPic() != null && infoData.getInfoPic().trim().length() > 0)
            infoDetailData.setLinkIcon(infoData.getInfoPic());
        if(infoData.getTitle() != null && infoData.getTitle().trim().length() > 0)
            infoDetailData.setLinkTitle(infoData.getTitle());
        if(infoData.getId() != null && infoData.getId().trim().length() > 0)
            infoDetailData.setLinkId(infoData.getId());
        if(infoData.getType() != infoDetailData.getLinkType())
            infoDetailData.setlinkType(infoData.getType());

        String html = infoData.getHtml();if(!TextUtils.isEmpty(html)&&html.length()>10){//有详情
            jpWebView.loadDetailHtml(html, infoData.getSource(), infoData.getAuthorName(), infoData.getUrl(), infoData.getNotice());
            if(!TextUtils.isEmpty(infoData.getQiniuUrl()))
                talkBottomView.setContentViewStyle(3);
            else
                talkBottomView.setContentViewStyle(0);
            setTextSizeBtn.setVisibility(View.VISIBLE);
            copyrightBtn.setVisibility(View.GONE);
        }else if(!TextUtils.isEmpty(infoData.getQiniuUrl())){//有附件 没有详情
            setScreenAcross();//设置手机可以横屏
//                jpWebView.loadUrl( "http://dcsapi.com?k=" + "113584176" + "&url=" + URLEncoder.encode(infoData.getQiniuUrl(),"utf-8"));
            if(TextUtils.isEmpty(infoData.getInfoPic())) {
                jpWebView.loadUrl(infoData.getQiniuUrl());
            } else{
                showContentImg(infoData);
            }
            talkBottomView.setContentViewStyle(0);
            if(permissionRemindView.getVisibility() == View.GONE)
                copyrightBtn.setVisibility(View.VISIBLE);
            else
                copyrightBtn.setVisibility(View.GONE);
            if(infoData.getInfoOriginal() == 1)
                copyrightBtn.setText("原创");
            else
                copyrightBtn.setText("版权");
            setTextSizeBtn.setVisibility(View.GONE);
        }else{//没详情也没附件 打开外网
            jpWebView.loadUrl(infoData.getUrl());
            talkBottomView.setContentViewStyle(0);
            if(permissionRemindView.getVisibility() == View.GONE) {
                copyrightBtn.setVisibility(View.VISIBLE);
                setTextSizeBtn.setVisibility(View.GONE);
            } else {
                copyrightBtn.setVisibility(View.GONE);
                setTextSizeBtn.setVisibility(View.VISIBLE);
            }
        }
        if(infoData.getType() == 25) {
            talkBottomView.setContentViewStyle(4);
            toolsPopupWindow.setData(infoData.getAppList());
        }

        copyrightDialog.setDesc(infoData.getNotice());
        copyrightDialog.setOpenUrl(infoData.getUrl());
        copyrightDialog.setTitle(infoData.getAuthorName());
        copyrightDialog.setTag(infoData.getSource());

//        if ((html == null || html.trim().length() < 10)&&TextUtils.isEmpty(infoData.getQiniuUrl())) {
//            jpWebView.loadUrl(infoData.getUrl());
//        }else if((html == null || html.trim().length() < 10)&& !TextUtils.isEmpty(infoData.getQiniuUrl())){
//            jpWebView.loadUrl(  "http://dcsapi.com?k=" + "113584176" + "&url=" + infoData.getQiniuUrl());
//        } else {
//            jpWebView.loadDetailHtml(html, infoData.getAuthorIcon(), infoData.getAuthorName(), infoData.getUrl());
//        }

        sharePopupWindow.visibilityDownload(!TextUtils.isEmpty(infoData.getQiniuUrl()));
    }

    private void showContentImg(InfoData infoData){
        final List<String> imgPaths = new ArrayList<>();
        if(infoData.getInfoPic().endsWith(".svg.png")){
            String baseImgPath = infoData.getInfoPic().substring(0, infoData.getInfoPic().length() - 9);
            for (int i = 1; i <= infoData.getPageCount(); i++) {
                String imgPath = baseImgPath + i + ".svg";
                imgPaths.add(imgPath);
            }
            showSvgImgs(imgPaths);
            return;
        }
        jpWebView.setVisibility(View.GONE);
        mainRvFrame.setVisibility(View.VISIBLE);
        mainRv.setHasFixedSize(true);
        final LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        mainRv.setLayoutManager(layoutManager);

        String baseImgPath = infoData.getInfoPic().substring(0, infoData.getInfoPic().length() - 1);
        for (int i = 1; i <= infoData.getPageCount(); i++) {
            String imgPath = baseImgPath + i
                    + (infoData.getWidth() < 1920
                    ? "?imageMogr2/format/jpg"
                    : "?imageMogr2/format/jpg/thumbnail/!30p");
            imgPaths.add(imgPath);
        }

        int itemHeight = 0;
        if(infoData.getWidth() > 0 && infoData.getHeight() > 0){
            int screenWidth = getResources().getDisplayMetrics().widthPixels;
            itemHeight = screenWidth * infoData.getHeight() / infoData.getWidth();
        }
        InfoDataDetailImgAdapter imgAdapter = new InfoDataDetailImgAdapter(mContext, imgPaths, itemHeight);
        mainRv.setAdapter(imgAdapter);
        imgAdapter.addItemClickListener(new RecycleVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
                ImagePreviewActivity.startActivity(mContext, position, (ArrayList<String>) imgPaths);
            }
        });
//        mainRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//                mainRvText.setText(layoutManager.findFirstVisibleItemPosition()+1 + "/" + imgPaths.size());
//            }
//        });
        mainRvText.setText(imgPaths.size()+"");
    }

    private void showSvgImgs(List<String> imgPaths){
        jpWebView.loadSvgImgs(imgPaths);
    }

    /***
     * 设置手机可以横屏
     */
    private void setScreenAcross() {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Checks the orientation of the screen
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {//横屏
          talkBottomView.setVisibility(View.GONE);
            ParallaxHelper.disableParallaxBack(this);
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){//竖屏
            talkBottomView.setVisibility(View.VISIBLE);
            ParallaxHelper.enableParallaxBack(this);
        }
        moreBtnPopupWindow.dismiss();
        fontSelectDialog.dismiss();
        sharePopupWindow.dismiss();
        toolsPopupWindow.dismiss();
        commentDialog.dismiss();
        copyrightDialog.dismiss();
    }

    /* 底部栏回调 */
    @Override
    public void viewNeedToUpdate(int requestType, boolean isSuccess) {
        // 话题提交成功并且是抢开话题，需要重新获取一遍话题数据
        if(requestType == TalkBottomBarView.COMMIT_COMMENT_CODE
                && isSuccess
                && (infoDetailData.getTopicInfo().getTopicId() == null
                || infoDetailData.getTopicInfo().getTopicId().trim().length() == 0)){
            getDataUtil.getTopicData();
        } else if(isSuccess && (requestType == TalkBottomBarView.COLLECTION_CODE
                || requestType == TalkBottomBarView.CANCEL_COLLECTION_CODE)){
//            localBroadcastManager.sendBroadcast(new Intent(LocalBroadCast.DETAIL_SC_BROAD)
//                    .putExtra("id", infoDetailData.getLinkId())
//                    .putExtra("isCollection", infoDetailData.getTopicInfo().getIsCollection()));
        }
    }


    /* 获取数据完成后的回调 */
    @Override
    public void onFinish(int requestCode, boolean isSuccess) {
        if(requestCode == ToutiaoGetDataUtil.GET_DETAIL_DATA){
            if(isSuccess){
                setPermissionView();
                setDetailData();
                if(isToDownload){
                    toDownload();
                    isToDownload = false;
                }
            } else{
                ToasUtil.toast(this, "抱歉，数据加载出错");
                hideDataLoading(true);
            }
        } else if(requestCode == ToutiaoGetDataUtil.GET_TOPIC_DATA){
            if(isSuccess)
                talkBottomView.updateView();
            else
                ToasUtil.toast(this, "抱歉，话题数据获取失败");
        } else if(requestCode == ToutiaoGetDataUtil.GET_DETAIL_STATE){
            if(isSuccess)
                talkBottomView.updateView();
        }
    }

    private void setTextSizeLevel(int textSizeLevel){
        TextSize textSize;
        switch (textSizeLevel){
            case 0:     textSize = TextSize.SMALLER;    break;
            case 1:     textSize = TextSize.NORMAL;     break;
            case 2:     textSize = TextSize.LARGER;     break;
            case 3:     textSize = TextSize.LARGEST;    break;
            default:    textSize = TextSize.SMALLER;
        }
        jpWebView.getWebSettings().setTextSize(textSize);
        sharedPreferences.edit().putInt("textSizeLevel", textSizeLevel).apply();;
        LocalBroadcastManager.getInstance(mContext).sendBroadcast(new Intent(LocalBroadCast.COMM_CHANGE_SIZE));
    }

    private int getTextSizeLevel(){
        return sharedPreferences.getInt("textSizeLevel", 1);
    }

    @Override
    public void onStart(int requestType) {
        loading.show();
    }
    @Override
    public void onCompleted(int requestType) {
        loading.cancel();
    }
    @Override
    public void onError(int requestType) {
        onCompleted(requestType);
    }
    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0){
            ToasUtil.toast(mContext, data.getMessage());
            onError(requestType);
        } else if(requestType == COMMETN_CODE){
            ToasUtil.toast(mContext, "评论成功");
            InfoDetailStateModel infoDetailStateModel = infoDetailData.getInfoDetailStateModel();
            infoDetailStateModel.setCommentCount(infoDetailStateModel.getCommentCount()+1);
            commentDialog.clearEditContent();
            talkBottomView.updateView();
        } else if(requestType == PAY_CODE){
            permissionView.setVisibility(View.GONE);
            permissionRemindView.setVisibility(View.VISIBLE);
            showDataLoading();
            getDataUtil.getDetailData();
        }
    }
}
